<?php

namespace app\common\services\token\driver;

use app\common\model\user\UserToken;
use app\common\services\token\Driver;
use think\facade\Cache;

/**
 * Token操作类
 */
class Mysql extends Driver
{

    /**
     * 默认配置
     * @var array
     */
    protected $options = [
        'expire' => 2592000,
    ];
    /**
     * @var UserToken
     */
    private UserToken $Model;

    /**
     * 构造函数
     * @param array $options 参数
     * @access public
     */
    public function __construct($options = [])
    {
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $this->Model = new UserToken();
        $this->clearExpireTime();
    }

    /**
     * 自动清除已经过期的token
     */
    private function clearExpireTime()
    {
        $time = time();
        $clear_time = Cache::get('clear_token_time');
        if (!$clear_time || $clear_time < $time - 86400) {
            Cache::set('clear_token_time', $time);
            $this->Model->where('expire_time', '<', time())->where('expire_time', '>', 0)->delete();
        }
    }

    /**
     * 存储Token
     * @param string $token Token
     * @param int $uid 会员ID
     * @param int $expire 过期时长,0表示无限,单位秒
     * @return bool
     */
    public function set($token, $uid, $expire = 0)
    {
        $expire_time = !is_null($expire) && $expire !== 0 ? time() + $expire : 0;
        $token = $this->getEncryptedToken($token);
        $this->Model->save([
            'token'       => $token,
            'expire_time' => $expire_time,
            'uid'         => $uid
        ]);
        return true;
    }

    /**
     * 获取Token内的信息
     * @param string $token
     * @return  array
     */
    public function get($token)
    {
        $data = $this->Model->where('token', $this->getEncryptedToken($token))->find();
        if ($data) {
            if (!$data['expire_time'] || $data['expire_time'] > time()) {
                return $data['uid'];
            } else {
                self::delete($token);
            }
        }
        return [];
    }

    /**
     * 判断Token是否正确
     * @param string $token Token
     * @param int $uid 会员ID
     * @return  boolean
     */
    public function check($token, $uid)
    {
        $data = $this->get($token);
        return $data && $data['uid'] == $uid ? true : false;
    }

    /**
     * 删除Token
     * @param string $token
     * @return  boolean
     */
    public function delete($token)
    {
        $this->Model->where('token', $this->getEncryptedToken($token))->delete();
        return true;
    }

    /**
     * 删除指定用户的所有Token
     * @param int $uid
     * @return  boolean
     */
    public function clear($uid)
    {
        $this->Model->where('uid', $uid)->delete();
        return true;
    }
}
